package com.orangelife.mobile.parkingcard.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.sp.UserSp;
import com.curry.android.http.OrangeHttpConstant;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.verify.biz.SmsHttpBiz;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.ParkingCardURL;
import com.orangelife.mobile.parkingcard.biz.ParkingCardHttpBiz;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by yyx
 * on 2015/11/17.
 */
public class ParkingAuthenticationActivity extends OrangeLifeBaseActivity implements View.OnClickListener {
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.etName)
    EditText etName;
    @Bind(R.id.etPhone)
    EditText etPhone;
    @Bind(R.id.etVerifyCode)
    EditText etVerifyCode;
    @Bind(R.id.tvObtainCode)
    TextView tvObtainCode;
    @Bind(R.id.tvVoiceCode)
    TextView tvVoiceCode;
    @Bind(R.id.btnSubmit)
    Button btnSubmit;
    @Bind(R.id.llTip)
    LinearLayout llTip;

    private int timeSendSms = 59;
    private Timer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_authentication);
        ButterKnife.bind(this);
        findView();
        setName();
    }


    private void setName() {
        if (UserSp.hasCert()) {
            etName.setText(UserSp.getCertName());
            etName.setEnabled(false);
            llTip.setVisibility(View.VISIBLE);
        } else {
            etName.setText("");
            etName.setEnabled(true);
            llTip.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化赋值
     */
    private void findView() {
        tvTitle.setText("身份认证");
        etPhone.setText(UserSp.getRegPhone());
        tvObtainCode.setOnClickListener(this);
        tvVoiceCode.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        String phone = etPhone.getText().toString();
        switch (view.getId()) {

            case R.id.tvObtainCode:

                if (StringUtil.isBlank(etPhone.getText().toString())) {
                    ToastHelper.getInstance()._toast("请输入手机号！");
                } else if (etPhone.getText().length() != 11) {
                    ToastHelper.getInstance()._toast("请输入正确的手机号！");
                } else {
                    if (isConnected()) {
                        dialog = DialogHelper.getInstance().createLoadingDialog(
                                ParkingAuthenticationActivity.this,
                                getResources().getString(
                                        R.string.register_request_vercode));
                        dialog.show();
                        SmsHttpBiz.getSmsCode(phone, mHandler, 0);
                        countDownSendSmsAgain();
                    }
                }
                break;
            case R.id.tvVoiceCode:
                if (StringUtil.isBlank(etPhone.getText().toString())) {
                    ToastHelper.getInstance()._toast("请输入手机号！");
                } else if (etPhone.getText().length() != 11) {
                    ToastHelper.getInstance()._toast("请输入正确的手机号！");
                } else {
                    if (isConnected()) {
                        dialog = DialogHelper.getInstance().createLoadingDialog(
                                ParkingAuthenticationActivity.this,
                                getResources().getString(
                                        R.string.register_request_vercode));
                        dialog.show();
                        SmsHttpBiz.getVoiceCode(phone, mHandler);
                        countDownSendSmsAgain();
                    }
                }
                break;
            case R.id.btnSubmit:
                String name = etName.getText().toString();
                phone = etPhone.getText().toString();
                String code = etVerifyCode.getText().toString();
                if (StringUtil.isBlank(etName.getText().toString())) {
                    ToastHelper.getInstance()._toast("请输入姓名！");
                } else if (StringUtil.isBlank(etPhone.getText().toString())) {
                    ToastHelper.getInstance()._toast("请输入手机号！");
                } else if (StringUtil.isBlank(etVerifyCode.getText().toString())) {
                    ToastHelper.getInstance()._toast("请输入手机验证码！");
                } else {
                    if (isConnected()) {
                        dialog = DialogHelper.getInstance().createLoadingDialog(
                                ParkingAuthenticationActivity.this, "正在提交，请稍后...");
                        dialog.show();
                        sendRequestForRegister(name, phone, code);
                    }
                }
                break;
        }
    }

    private void sendRequestForRegister(String name, String phone,
                                        String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("name", name);
        map.put("identity", "0");
        map.put("code", code);
        ParkingCardHttpBiz.requesPost(map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                DialogHelper.closeDialog(dialog);
                if (errCode == OrangeHttpConstant.RESULT_SUCCESS) {
                    ToastHelper.getInstance()._toast("私有车位认证成功！");
                    finish();
                } else if (errCode == 98) {
                    Map<String, Object> map = JSONHelper.jsonToMap(response.toString());
                    if (map != null) {
                        String errInfo = String.valueOf(map.get(OrangeHttpConstant.RESULT_MESSAGE_KEY));
                        if (!StringUtil.isBlank(errInfo)) {
                            ToastHelper.getInstance()._toast(errInfo);
                        }
                    }
                } else if (errCode == 73003 || errCode == 71002) {/*73003=没有认证*/
                    Map<String, Object> responseError = JSONHelper.jsonToMap(response.toString());
                    if (responseError != null) {
                        Map<String, Object> entity = JSONHelper.jsonToMap(String.valueOf(responseError.get(OrangeHttpConstant.RESULT_KEY_ENTITY)));
                        if (entity != null) {
                            String phone = String.valueOf(entity.get("phone"));
                            if (!StringUtil.isBlank(phone)) {
                                IntentHelper.getInstances().intentWithExtra(ParkingAuthenticationActivity.this, ParkingAuthenticationErrorActivity.class, "phone", phone);
                                finish();
                            }
                        }
                    }
                } else {
                    Map<String, Object> map = JSONHelper.jsonToMap(response.toString());
                    if (map != null) {
                        String errInfo = String.valueOf(map.get(OrangeHttpConstant.RESULT_MESSAGE_KEY));
                        if (StringUtil.isBlank(errInfo)) {
                            ToastHelper.getInstance()._toast(errInfo);
                        }
                    }
//                    ToastHelper.getInstance()._toast("认证失败"+response.toString());
                }
            }
        }, ParkingCardURL.PRIVATE_IDENTIFY);

    }

    /**
     * 重置验证码时间
     */
    private void countDownSendSmsAgain() {
        /* 点击发送验证码后进行倒计时 */
        timeSendSms = 59;
        tvVoiceCode.setEnabled(false);
        tvObtainCode.setEnabled(false);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.obtainMessage(Constant.WHAT_COUNT_DOWN, timeSendSms--)
                        .sendToTarget();
            }
        }, 0, 1000);
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.WHAT_COUNT_DOWN:
                    if (timeSendSms >= 0) {
                        tvObtainCode.setText(getResources().getString(R.string.wait)
                                + timeSendSms
                                + getResources().getString(R.string.seconds));
                        tvVoiceCode.setText(getResources().getString(R.string.wait)
                                + timeSendSms
                                + getResources().getString(R.string.seconds));
                    } else {
                        tvObtainCode.setEnabled(true);
                        tvVoiceCode.setEnabled(true);
                        tvObtainCode.setText(getResources().getString(
                                R.string.send_again));
                        tvVoiceCode.setText(getResources().getString(
                                R.string.voice_code));
                        timer.cancel();
                    }
                    break;
                case 0:
                    DialogHelper.closeDialog(dialog);
                    if (msg.obj != null) {
                        HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                                .jsonToMap(String.valueOf(msg.obj));
                        if (map != null) {
                            int errCode = Integer.parseInt(map.get(
                                    Constant.RESULT_KEY).toString());
                            String errInfo = String.valueOf(map
                                    .get(Constant.RESULT_MESSAGE_KEY));
                            if (errCode == Constant.RESULT_SUCCESS) {
                                ToastHelper.getInstance()
                                        .displayToastWithQuickClose(
                                                ParkingAuthenticationActivity.this.getResources().getString(
                                                        R.string.send_sms_success));
                            } else {
                                ToastHelper.getInstance()
                                        .displayToastWithQuickClose(errInfo);
                                timeSendSms = 0;
                            }
                        }
                    } else {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(R.string.send_sms_fail));
                        timeSendSms = 0;
                    }
                    break;
                case SmsHttpBiz.WHAT_VOICE_CODE:
                    DialogHelper.closeDialog(dialog);
                    if (msg.obj != null) {
                        HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                                .jsonToMap(String.valueOf(msg.obj));
                        if (map != null) {
                            int errCode = Integer.parseInt(map.get(
                                    Constant.RESULT_KEY).toString());
                            String errInfo = String.valueOf(map
                                    .get(Constant.RESULT_MESSAGE_KEY));
                            if (errCode == Constant.RESULT_SUCCESS) {
                                ToastHelper.getInstance()
                                        .displayToastWithQuickClose(
                                                getResources().getString(
                                                        R.string.send_voice_success));
                            } else {
                                ToastHelper.getInstance()
                                        .displayToastWithQuickClose(errInfo);
                                timeSendSms = 0;
                            }
                        }
                    } else {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(R.string.send_voice_fail));
                        timeSendSms = 0;
                    }
                    break;
                default:
                    break;
            }
        }

    };
}
